<?php
/*
 * @Author: your name
 * @Date: 2019-12-25 09:53:48
 * @LastEditTime : 2020-01-17 10:23:52
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /ahsmp_3/application/timeexecution/service/Netfilter/Log.php
 */
namespace app\timeexecution\service\Netfilter;

use app\common\model\access_log\HostAccessLogModel;
use app\timeexecution\service\Base;
use think\Db;

class LogClear extends Base
{
    private $path = '../runtime/timexec/';//定时文件存放路径
    private $fileName = 'netfilterLogclear.lock';//文件名

    /**
     * @name: 清理
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-25 14:11:21
     */

    public function clear ()
    {
        $this->checkNetfilter();
        $this->wirteLock($this->path, $this->fileName);
        $hostConfig = $this->selectHost();
        //分库模式的查询方式
        $logModel = new HostAccessLogModel();
        foreach ($hostConfig as $v)
        {
            if($v['process'] == 1)
            {
                $time = time() - $v['expired_time'];
                $logModel->setHostId($v['host_id']);
                $logModel->where('first_time', '<', $time)->delete();
            }
            
        }
        $this->delLock($this->path . $this->fileName);
    }

    /**
     * @name: 查询主机
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2019-12-25 14:16:17
     */
    public function selectHost()
    {
        $return = Db::name('HostModuleRelation')->field('halc.host_id,halc.expired_time,halc.process')->alias('hmr')->join('HostAccessLogConfig halc', 'hmr.host_id=halc.host_id')->where('hmr.netfilter', 1)->select();

        return $return;
    }

    /**
     * @name: 检测是否存在netfilter
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-01-15 16:07:04
     */
    public function checkNetfilter ()
    {
        $table_a = Db::query('SHOW COLUMNS FROM ' . config('database.prefix') . 'host_module_relation' );

        if(empty($table_a))
        {
            echo '程序未初始化';
            die;
        }

        $field = array_column($table_a, 'Field');
        if(!array_search('netfilter', $field))
        {
            echo '未开启该模块';
            die;
        }
    }
}
